/*
    created: 2023/4/11
    filename: liststack.c
    author: 李东霖
    purpose： 使用链表实现栈 带头结点 
*/
#include"liststack.h"

//初始化  
int InitStack1(PListStack *s)
{
    if(*s != NULL) return -1;
    *s = (PListStack)malloc(sizeof(SNode));
    if(*s == NULL) return 0;
    (*s)->next = NULL;
    return 1;
} 
//初始化  
SNode* InitStack2()
{
    SNode* s = (PListStack)malloc(sizeof(SNode));
    if(s == NULL) return NULL;
    s->next = NULL;
    return s;

}


//销毁栈 
void DistroyStack(PListStack *s)
{
    SNode* p = *s;
    SNode* del;
    while(p != NULL)
    {
        del = p;
        p = p->next;
        free(del);
    }       
    *s = NULL;
} 
//清空栈 
void ClearStack(PListStack s)
{
    if(s == NULL || s->next == NULL) return ;
    SNode* p = s->next;
    SNode* del;
    while(p != NULL)
    {
        del = p;
        p = p->next;
        free(del);
    }
    s->next = NULL;
}

//求栈的长度 返回值：-1-传入的指针为NULL 0-空栈 >0-长度
int LengthStack(PListStack s)
{
    if(s == NULL) return -1;
    int length = 0;
    SNode* p = s;
    while(p->next != NULL)
    {
        ++length;
        p = p->next;
    }
    return length;
}

//判断栈空 返回值 1-空 0-非空 -1-传入栈是空的
int StackEmpty(PListStack s)
{
    if(s == NULL) return -1;
    return s->next == NULL;

}
 
//将元素压入栈顶 返回值 1-成功 0-失败 -1-传入栈是空的
int Push(PListStack s,ElemType *e)
{
    if(s == NULL) return -1;  
    if(e == NULL) return -1;
    SNode* temp = (SNode*)malloc(sizeof(SNode));
    if(temp == NULL) return 0;
    memcpy(&temp->data,e,sizeof(ElemType));
    temp->next = s->next;
    s->next = temp; 
    return 1;
} 
//将栈顶元素出栈存放到e中  返回值 1-成功 0-失败 -1-传入栈是空的
int Pop(PListStack s,ElemType *e)
{
    if(e == NULL) return -1;
    if(!StackEmpty(s))
    {
        SNode* temp = s->next;
        memcpy(e,&temp->data,sizeof(ElemType));
        s->next = s->next->next;
        free(temp);
        return 1;
    }
    return 0;
}
//得到栈顶元素  
int GetTop(PListStack s,ElemType *e)
{
    if(e == NULL) return -1;
    if(!StackEmpty(s))
    {
        SNode* temp = s->next;
        memcpy(e,&temp->data,sizeof(ElemType));
        return 1;
    }
    return 0;    

}

//打印这个栈
void DispStack(PListStack s)
{
    if(s == NULL) return;
    SNode* p = s->next;
    while(p != NULL)
    {
        printf("%d  ",p->data);
        p = p->next;
    }
}